package user

import (
	"cms/model"
	service "cms/serivce"
	"engine/cache"
	"engine/consts"
	"engine/dto"
	emodel "engine/model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"golang.org/x/net/context"
	"gorm.io/gorm"
	"lib/db"
	"lib/log"
	"lib/middleware"
	"lib/response"
	sferrors "lib/sf-errors"
	"net/http"
	"strconv"
	"time"
)

// GetGiftPage 礼包
// @Summary		礼包
// @Description	礼包
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/gift_page [GET]
func (handler *AccountHandler) GetGiftPage(ctx *gin.Context) {

	var operator *emodel.SysUserDetail
	userID, _, err := middleware.ProcessToken(ctx, consts.AdminAuthKey)
	if err == nil {
		operator, err = dto.GetCachedActiveSysUserById(ctx, userID)
		if err != nil {
			log.Errorf("获取用户失败：%v", err)
			response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError).SetHttpStatus(http.StatusInternalServerError))
			ctx.Abort()
			return
		}
	}

	var userLevel emodel.My_user_levels
	if userID > 0 {
		db.GetDb().Where("uid=? and days=?", operator.Id, time.Now().Format("20060102")).Order("id desc").First(&userLevel)
	}

	level := 1
	if userLevel.Id > 0 {
		level = userLevel.Levels + 1
	}

	var staircase []model.UserStaircase
	if err = db.GetDb().Find(&staircase).Error; err != nil {
		response.Error(ctx, sferrors.NewString("非法操作"))
		return
	}
	//支付时限 10/15/20/25/29/34/37/41
	for i, i2 := range staircase {
		if level > i2.Id {
			staircase[i].IsTrue = true
		} else {
			staircase[i].IsTrue = false
		}
		zz, zhuangtai := checkPay(ctx, operator.CreateTime, i2.Id, operator.Id, operator.T)
		if zz == true {
			staircase[i].IsPay = true
			//staircase[i].EndTime = zhuangtai
		}
		if zhuangtai != nil {
			staircase[i].EndTime = zhuangtai
		}

	}
	response.OkData(ctx, staircase)
}

// GetGiftPage111 礼包
// @Summary		礼包
// @Description	礼包
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/gift_page111/{index}/{page} [GET]
func (handler *AccountHandler) GetGiftPage111(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if pageInt == 0 {
		pageInt = 1
	}

	index := ctx.Param("index")
	indexInt, err := strconv.Atoi(index)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	query := db.GetDb()
	query = query.Where("uid=? and status=?", operator.Id, indexInt)
	query = query.Order("id desc")

	list, err := dto.Paginate[emodel.My_online_order_levels](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 15,
	})
	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	response.OkData(ctx, list)
}

func checkPay(ctx context.Context, createTime string, id int, uid uint64, tt int) (bool, *time.Time) {

	//cache.RedisContextSet(ctx, "user_create_time_pay", time.Now().Unix(), 0)
	starTime, err := cache.RedisContextGet[int64](ctx, "user_create_time_pay")
	if err != nil || starTime == nil {
		return false, nil
	}
	loc, _ := time.LoadLocation("Asia/Shanghai")
	endTime, err := time.ParseInLocation("2006-01-02T15:04:05", createTime[:19], loc)
	if err != nil {
		return false, nil
	}

	//是否进行时间判断
	if tt == 0 { //
		if *starTime < endTime.Unix() {
			return false, nil
		}
	} else if tt == 1 { //1 可以不传订单
		return false, nil
	}

	mats := map[int]bool{
		10: true,
		15: true,
		20: true,
		25: true,
		29: true,
		34: true,
		37: true,
		41: true,
	}
	data, ok := mats[id]
	if ok == true && data == true {

		key := fmt.Sprintf("new1%d_%d", id, uid)
		datas, err := cache.RedisContextGet[time.Time](ctx, key)
		if err == nil && datas != nil {
			return false, datas
		}
		return true, nil
	}

	return false, nil
}

func (handler *AccountHandler) BuyPackageNewTow(ctx *gin.Context) {
	response.Error(ctx, sferrors.NewString("请卸载后重新下载"))
	return
}

func (handler *AccountHandler) BuyPackageNewThire(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	var req model.BuyPackage
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}

	if operator.DyTure == 0 {
		response.Error(ctx, sferrors.NewString("需要先认证"))
		return
	}

	//if (req.Index == 1 || req.Index%10 == 0) && operator.N == 0 {
	//	if req.AuthCode == "" {
	//		response.Error(ctx, sferrors.NewString("需要支付宝授权"))
	//		return
	//	}
	//	err = service.CheckOpenid(req.AuthCode, operator.My_user)
	//	if err != nil {
	//		response.Error(ctx, sferrors.NewStringf("请重新授权： "+err.Error()))
	//		return
	//	}
	//}

	hour, _ := strconv.Atoi(time.Now().Format("1504"))
	if hour >= 2359 || hour < 300 {
		response.Error(ctx, sferrors.NewString("23:59-03:00不能参与"))
		return
	}

	var userLevel emodel.My_user_levels
	days, _ := strconv.Atoi(time.Now().Format("20060102"))

	db.GetDb().Where("uid=? and days=?", operator.Id, days).Order("id desc").First(&userLevel)

	level := 1
	if userLevel.Id > 0 {
		level = userLevel.Levels + 1
	}
	if operator.L > 0 {
		if level > operator.L {
			response.Error(ctx, sferrors.NewStringf("目前只开放到%d阶梯", int(operator.L)))
			return
		}
	}

	zz, _ := checkPay(ctx, operator.CreateTime, level, operator.Id, operator.T)
	if zz == true {
		response.Error(ctx, sferrors.NewString("请确认是否上传订单"))
		return
	}

	//if level > 42 {
	//	if cachedID, redisErr := db.GetRedisClient().Get(ctx, "pay_switch").Int(); redisErr != nil {
	//
	//	} else if cachedID == 1 {
	//		nowTimeEnd := time.Now().Format("20060102")
	//		IntNow, _ := strconv.Atoi(nowTimeEnd)
	//		//检查是否需要购买
	//		if operator.EndDate < IntNow {
	//			response.Error(ctx, sferrors.NewString("需要购买"+strconv.Itoa(operator.OldLevel)+"阶(含以上)产品"))
	//			return
	//		}
	//	}
	//}
	endL, _ := cache.RedisContextGet[int](ctx, "s_l")

	if level > *endL {
		response.Error(ctx, sferrors.NewStringf("目前只开放到%d阶梯", *endL))
		return
	}

	if level != req.Index {
		response.Error(ctx, sferrors.NewString(fmt.Sprintf("必须先参与 %d级阶梯", level)))
		return
	}

	var staircase *model.UserStaircase
	if err = db.GetDb().Where("id=?", req.Index).First(&staircase).Error; err != nil {
		response.Error(ctx, sferrors.NewString("非法操作"))
		return
	}
	buyMoney := staircase.NeedNum

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser).Error
		if txErr != nil {
			return txErr
		}
		if req.Type == 0 {
			if myUser.Money < buyMoney {
				return sferrors.NewStringf("您的 通用积分 余额 不足")
			}
			txErr = service.CreateUserLog(tx, myUser, buyMoney, 13, 0, fmt.Sprintf("通用积分 参与 %d级阶梯 上墙", staircase.Id))
			if txErr != nil {
				return txErr
			}
		} else {
			if myUser.Score < buyMoney {
				return sferrors.NewStringf("您的 备用积分 余额 不足")
			}
			txErr = service.CreateUserScoreLog(tx, myUser, buyMoney, 13, 0, fmt.Sprintf("备用积分 参与 %d级阶梯 上墙", staircase.Id))
			if txErr != nil {
				return txErr
			}
		}

		if staircase.IsNow == 1 {
			txErr = service.CreateUserLog(tx, myUser, buyMoney+staircase.Num, 14, 0, fmt.Sprintf(" 参与 %d级阶梯 上墙收益", staircase.Id))
			if txErr != nil {
				return txErr
			}
		}
		var newUserLevel emodel.My_user_levels
		//新增
		newUserLevel.Levels = level
		newUserLevel.Days = days
		newUserLevel.Uid = operator.Id
		newUserLevel.IsNow = staircase.IsNow
		newUserLevel.Num = staircase.NeedNum
		newUserLevel.ZNum = staircase.NeedNum + staircase.Num

		if err = tx.Create(&newUserLevel).Error; err != nil {
			return err
		}
		service.EsCreateUserLevelsData(newUserLevel)

		myUserMobile := myUser.Mobile[:3] + "******" + myUser.Mobile[len(myUser.Mobile)-4:]
		if myUser.Pid > 0 && req.Index > 0 {
			var pUser emodel.My_user
			txErr = tx.Where("id=? and j=0", myUser.Pid).First(&pUser).Error
			if txErr == nil {
				if pUser.OldLevel >= level {
					pAddMoney := staircase.Num * 0.2
					txErr = service.CreateUserLog(tx, pUser, pAddMoney, 5, 0, fmt.Sprintf("直推【%s】参与阶梯奖励【%d阶级】", myUserMobile, staircase.Id))
					if txErr != nil {
						return txErr
					}
				}
			}
		}
		if myUser.Ppid > 0 && req.Index > 0 {
			var pPUser emodel.My_user
			txErr = tx.Where("id=? and j=0", myUser.Ppid).First(&pPUser).Error
			if txErr == nil {
				if pPUser.OldLevel >= level {
					ppAddMoney := staircase.Num * 0.1
					txErr = service.CreateUserLog(tx, pPUser, ppAddMoney, 5, 0, fmt.Sprintf("间推【%s】参与阶梯奖励【%d阶级】", myUserMobile, staircase.Id))
					if txErr != nil {
						return txErr
					}
				}
			}
		}
		//if myUser.IsTask == 0 {
		//	if err = tx.Table("my_user").Where("id=?", myUser.Id).UpdateColumn("is_task", 1).Error; err != nil {
		//		return err
		//	}
		//}
		//level
		txErr = tx.Table("my_user").Where("id=?", myUser.Id).UpdateColumn("level", level).Error
		if txErr != nil {
			return txErr
		}

		if level == 20 {
			txErr = tx.Exec("update my_user set tl=tl+1  where id=? ", myUser.Id).Error
			if txErr != nil {
				return txErr
			}
		}
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}

	response.OkData(ctx, "操作成功！")
}

// GetMyRunPackage 我的运行中的礼包
// @Summary		礼包
// @Description	礼包
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/package/{type}/{page} [GET]
func (handler *AccountHandler) GetMyRunPackage(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("type")
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if pageInt == 0 {
		pageInt = 1
	}

	query := db.GetDb()
	query = query.Where("uid=?", operator.Id)

	dayTime := time.Now().Format("20060102")
	day, err := strconv.Atoi(dayTime)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	if types == "run" {
		query = query.Where("days=? and z_num>0", day)
	}
	if types == "end" {
		query = query.Where("days<?", day)
	}
	query = query.Where("uid=?", operator.Id)
	query = query.Order("id desc")

	list, err := dto.Paginate[emodel.My_user_levels](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 15,
		ShowSQL:  true,
	})
	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	response.OkData(ctx, list)
}
func (handler *AccountHandler) OldGetMyRunPackage(ctx *gin.Context) {

	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	types := ctx.Param("type")
	page := ctx.Param("page")
	pageInt, err := strconv.Atoi(page)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if pageInt == 0 {
		pageInt = 1
	}

	query := db.GetDb()
	query = query.Where("uid=?", operator.Id)

	if types == "run" {
		query = query.Where("level<6 and day>day_h")
	}
	if types == "end" {
		query = query.Where("level<6 day<=day_h")
	}
	if types == "runMax" {
		query = query.Where("level=6")
	}
	list, err := dto.Paginate[emodel.My_may](query, &dto.PaginatorOption{
		Page:     pageInt,
		PageSize: 10,
		ShowSQL:  true,
	})
	if err != nil {
		log.Errorf("获取账单记录失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}
	response.OkData(ctx, list)
}

// GetMyPackage 我今天能领取的能量
// @Summary		我今天能领取的能量
// @Description	我今天能领取的能量
// @Tags		cms/accounts
// @Accept		json
// @Produce		json
// @Param		RequestQuery query model.QueryUserLogRequest true "Request Parameters"
// @Success		200 {object} response.Response[dto.PaginationList[emodel.SysUserLog]]
// @Router		/api/user/v2/package [GET]
func (handler *AccountHandler) GetMyPackage(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	dayTime := time.Now().Format("20060102")
	day, err := strconv.Atoi(dayTime)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	query := db.GetDb()
	query = query.Where("day > day_h and ll=0 and j=0 and uid=? and days<?", operator.Id, day).Group("level")
	//query = query.Where("(level=6) or (level<6 and end_time>?)", time.Now().Format("2006-01-02 15:04:05"))
	var myMay []*emodel.My_may
	//所有收益
	err = query.Select("sum(day_money)day_money", "z_day", "level").Find(&myMay).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}
	dayList := make(map[int]float64)
	for _, may := range myMay {
		if may.Level == 6 && may.ZDay >= day {
			continue
		}
		dayList[may.Level] = may.DayMoney
	}

	var myMayDetail emodel.My_may
	//账户余额
	err = db.GetDb().Debug().Select("sum(day_money)day_money").Where("uid=? and day>day_h and days=?", operator.Id, day).Find(&myMayDetail).Error
	if err != nil {
		response.Error(ctx, err)
		return
	}

	myPackage := model.MyPackage{
		Avatar:   operator.Avatar,
		Money:    operator.Money,
		DayMoney: myMayDetail.DayMoney,
		DayList:  dayList,
	}
	response.OkData(ctx, &myPackage)
}

//
//func (handler *AccountHandler) ZhuanZhang(ctx *gin.Context) {
//	operator, err := getOperator(ctx)
//	if err != nil {
//		response.Error(ctx, err)
//		return
//	}
//
//	if operator.DyTure == 0 {
//		response.Error(ctx, sferrors.NewString("需要先认证"))
//		return
//	}
//
//	types := ctx.Param("type")
//	if types != "0" && types != "1" {
//		response.Error(ctx, sferrors.NewString("参数错误"))
//		return
//	}
//
//	var myMay emodel.My_may
//	err = db.GetDb().Where("level=6 and uid=? and day>day_h?", operator.Id).First(&myMay).Error
//	if err != nil || myMay.Id == 0 {
//		response.Error(ctx, sferrors.NewString("未找到星途"))
//		return
//	}
//	var addMoney float64
//	addMoney = myMay.Price
//	dayTime := time.Now().Format("20060102")
//	day, err := strconv.Atoi(dayTime)
//	if err != nil {
//		log.Errorf("GetTaskCount err :%v")
//		response.Error(ctx, sferrors.NewString("系统错误"))
//		return
//	}
//	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
//		var myUser emodel.My_user
//		txErr := tx.Set("gorm:query_option", "FOR UPDATE").First(&myUser, operator.Id).Error
//		if txErr != nil {
//			return txErr
//		}
//
//		if types == "0" {
//			if operator.Money < addMoney {
//				response.Error(ctx, sferrors.NewString("可转入 通用积分 余额不足"))
//				return sferrors.NewStringf("可转入 通用积分 余额不足")
//			}
//			myUser.JMoney = myUser.JMoney + addMoney
//
//			tx.Table("my_may").Where("id=?", myMay.Id).UpdateColumn("j", 0)
//			tx.Table("my_may").Where("id=?", myMay.Id).UpdateColumn("z_day", day)
//			if txErr != nil {
//				return txErr
//			}
//
//			txErr = service.CreateUserLog(tx, &myUser, addMoney, 6, 0, "转入质押 通用积分")
//		} else {
//
//			if myUser.JMoney != addMoney {
//				response.Error(ctx, sferrors.NewString("没有可用质押通用积分"))
//				return sferrors.NewStringf("没有可用质押通用积分")
//			}
//			myUser.JMoney = myUser.JMoney - addMoney
//
//			tx.Table("my_may").Where("id=?", myMay.Id).UpdateColumn("j", 1)
//			tx.Table("my_may").Where("id=?", myMay.Id).UpdateColumn("z_day", 0)
//			if txErr != nil {
//				return txErr
//			}
//
//			txErr = service.CreateUserLog(tx, &myUser, addMoney, 7, 0, "转出质押通用积分")
//		}
//
//		if txErr != nil {
//			return txErr
//		}
//		return nil
//	})
//	if err != nil {
//		return
//	}
//	response.OkData(ctx, "操作成功")
//}

func (handler *AccountHandler) Exchange(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}
	if operator.Y == 1 {
		response.Error(ctx, sferrors.NewString("需要先进行身份认证"))
		return
	}
	//时间限制
	//hour, _ := strconv.Atoi(time.Now().Format("1504"))
	//if hour >= 2359 || hour < 300 {
	//	response.Error(ctx, sferrors.NewString("23:59-03:00不能参与"))
	//	return
	//}

	var req model.ReqExchange
	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}
	if req.Num.LessThan(decimal.NewFromFloat(1)) {
		response.Error(ctx, sferrors.NewString("最少需要兑换1个"))
		return
	}

	if operator.DyTure == 0 {
		response.Error(ctx, sferrors.NewString("需要先认证"))
		return
	}

	types := ctx.Param("type")
	if types != "score" && types != "point" {
		response.Error(ctx, sferrors.NewString("参数错误"))
		return
	}

	var addMoney float64
	ddd, _ := cache.RedisContextGet[int](ctx, "jifenzhuazneng")
	if operator.Ql != 0 && operator.Ql > 0 {
		ddd = &operator.Ql
	} else {

		ccc, _ := time.Parse("2006-01-02T15:04:05+08:00", operator.CreateTime)
		enTime := ccc.Unix() - 8*3600
		sDays, _ := cache.RedisContextGet[int64](ctx, "jifenzhuazneng_days")
		if enTime > *sDays {
			mmm1, _ := cache.RedisContextGet[int](ctx, "jifenzhuazneng")
			ddd = mmm1
		} else {
			mmm1, _ := cache.RedisContextGet[int](ctx, "jifenzhuazneng_s")
			ddd = mmm1
		}
	}
	if types == "score" {
		addMoney = req.Num.InexactFloat64() * 100 / float64(*ddd)
	} else {
		if req.Num.LessThan(decimal.NewFromFloat(100)) {
			response.Error(ctx, sferrors.NewString("最少需要兑换100个"))
			return
		}
		addMoney = req.Num.InexactFloat64() / 100 * float64(*ddd)
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {
		var myUser emodel.My_user
		txErr := tx.Where("id=?", operator.Id).First(&myUser, operator.Id).Error
		if txErr != nil {
			return txErr
		}

		if types == "score" {
			if myUser.Money < req.Num.InexactFloat64() {
				return sferrors.NewStringf("通用积分不足")
			}

			//通用转备用
			if service.CreateUserLog(tx, myUser, req.Num.InexactFloat64(), 11, 0, "通用积分兑换贡献积分") != nil {
				return txErr
			}
			if service.CreateUserPointLog(tx, myUser, addMoney, 11, 0, "通用积分兑换贡献积分") != nil {
				return txErr
			}
		} else {
			if myUser.Point < req.Num.InexactFloat64() {
				return sferrors.NewStringf("贡献积分不足")
			}

			if service.CreateUserPointLog(tx, myUser, req.Num.InexactFloat64(), 12, 0, "贡献积分兑换通用积分") != nil {
				return txErr
			}
			if service.CreateUserLog(tx, myUser, addMoney, 12, 0, "贡献积分兑换通用积分") != nil {
				return txErr
			}
		}

		if txErr != nil {
			return txErr
		}
		return nil
	})
	if err != nil {
		return
	}

	response.OkData(ctx, "操作成功")

}

func (handler *AccountHandler) ExchangeQr(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}

	var giftMoney emodel.My_order_dea
	err = db.GetDb().Where("id=? and uid=?", id, operator.Id).First(&giftMoney).Error
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	if giftMoney.Flag != 0 {
		response.Error(ctx, sferrors.NewString("状态错误"))
		return
	}

	pUser, err := dto.GetSysUserDetailById(giftMoney.Puid)
	if err != nil || pUser == nil {
		response.Error(ctx, sferrors.NewStringf("非法操作"))
		return
	}
	var goldRate int
	db.GetRedisClient().Get(ctx, "goldRate").Scan(&goldRate)

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := tx.Where("id=?", pUser.Id).First(&pUser).Error
		if txErr != nil {
			return txErr
		}
		txErr = service.CreateUserLog(tx, pUser.My_user, giftMoney.Money*0.95, 1, pUser.Id, "收到 "+fmt.Sprintf("%d", giftMoney.Uid)+" 的转赠")
		if txErr != nil {
			return txErr
		}
		if txErr = service.CreateUserPointLog(tx, pUser.My_user, giftMoney.Money*95, 1, pUser.Id, "收到 "+fmt.Sprintf("%d", giftMoney.Uid)+" 的转赠"); txErr != nil {
			return txErr
		}

		if txErr = service.CreateGoldLog(tx, operator.My_user, (giftMoney.Money*0.05)/float64(goldRate), 1, pUser.Id, "转赠给 "+fmt.Sprintf("%d 获得", giftMoney.Uid)); txErr != nil {
			return txErr
		}

		if txErr = db.GetDb().Table("my_order_dea").Where("id=?", id).UpdateColumn("flag", 1).Error; txErr != nil {
			return txErr
		}

		if txErr = db.GetDb().Table("my_order_dea").Where("id=?", id).UpdateColumn("qr_time", time.Now().Format("2006-01-02 15:04:05")).Error; txErr != nil {
			return txErr
		}
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "操作成功")

}

func (handler *AccountHandler) ExchangeQrTz(ctx *gin.Context) {
	operator, err := getOperator(ctx)
	if err != nil {
		response.Error(ctx, err)
		return
	}

	id := ctx.Param("id")
	if id == "" {
		log.Errorf("参数解析失败：%v", err)
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.InvalidParameter))
		return
	}

	var giftMoney emodel.My_order_dea_tz
	err = db.GetDb().Where("id=? and uid=?", id, operator.Id).First(&giftMoney).Error
	if err != nil {
		response.Error(ctx, sferrors.New(err).SetCode(sferrors.SystemError))
		return
	}

	if giftMoney.Flag != 0 {
		response.Error(ctx, sferrors.NewString("状态错误"))
		return
	}

	pUser, err := dto.GetSysUserDetailById(giftMoney.Puid)
	if err != nil || pUser == nil {
		response.Error(ctx, sferrors.NewStringf("非法操作"))
		return
	}

	err = db.GetDb().Transaction(func(tx *gorm.DB) error {

		txErr := tx.Where("id=?", pUser.Id).First(&pUser).Error
		if txErr != nil {
			return txErr
		}

		txErr = service.CreateTzLog(tx, pUser.My_user, giftMoney.Money, 51, pUser.Id, fmt.Sprintf("收到【%d】 的转赠", operator.Id))
		if txErr != nil {
			return txErr
		}

		if txErr = db.GetDb().Table("my_order_dea_tz").Where("id=?", id).UpdateColumns(map[string]any{
			"qr_time": time.Now().Format("2006-01-02 15:04:05"),
			"flag":    1,
		}).Error; txErr != nil {
			return txErr
		}
		return nil
	})
	if err != nil {
		response.Error(ctx, err)
		return
	}
	response.OkData(ctx, "操作成功")

}
